package com.cloudcc.mobile.util;

import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.content.Context;
import android.os.Handler;
import android.os.Message;

public class HttpServiceThread extends Thread {
	Context context;
	String urlPath;
	String params;
	Handler rHandler;

	public HttpServiceThread(Context context, String urlPath, String params,
			Handler rHandler) {
		this.context = context;
		this.urlPath = urlPath;
		this.params = params;
		this.rHandler = rHandler;
	}

	@Override
	public void run() {
		super.run();
		httpPost();
	}

	public void httpPost() {
		String result = null;
		try {
			URL url = new URL(urlPath);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setDoInput(true);
			conn.setConnectTimeout(8000);
			conn.setDoOutput(true);
			conn.setUseCaches(false);
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Charset", "UTF-8");
			conn.setRequestProperty("Content-type",
					"application/x-java-serialized-object");
			conn.connect();

			if (params != null) {
				OutputStream os = conn.getOutputStream();
				ObjectOutputStream oos = new ObjectOutputStream(os);
				oos.writeObject(params);
				oos.flush();
				oos.close();
				os.close();
			}

			int code = conn.getResponseCode();
			if (code == HttpURLConnection.HTTP_OK) {
				InputStream is = conn.getInputStream();
				ObjectInputStream inputStream = new ObjectInputStream(is);
				result = (String) inputStream.readObject();
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (result == null) {
				result = "";
			}
			Message msg = rHandler.obtainMessage();
			msg.obj = result;
			rHandler.sendMessage(msg);
		}
	}
}
